package com.jplus.core.mvc;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.core.AppConstant;
import com.jplus.core.core.ConfigHandle;
import com.jplus.core.core.CoreLoader;
import com.jplus.core.plugin.PluginHandle;
import com.jplus.core.util.FormatUtil;

/**
 * DispatcherServlet 异步Servlet处理
 * 
 * @author huangyong
 * @author Yuanqy
 *
 */
@WebServlet(urlPatterns = "/", loadOnStartup = 0, asyncSupported = true)
public class DispatcherServlet extends HttpServlet {
	public static Boolean isWeb = false;
	private static final long serialVersionUID = -4125107833350340877L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	// Servlet线程池
	// 我觉得用缓存线程池比较合适，有60s的缓存期。
	private ExecutorService es = Executors.newCachedThreadPool();

	// Servlet异步超时时间,默认超时30秒
	private int timeout;

	@Override
	public void init(ServletConfig config) throws ServletException {
		isWeb = true;
		ServletContext context = config.getServletContext();
		CoreLoader.init();
		addIgnoreMapping(context);
		this.timeout = ConfigHandle.getInt("app.timeout", 1000 * 30);
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		es.execute(new ServletThread(request.startAsync(), timeout));
	}

	@Override
	public void destroy() {
		super.destroy();
		try {
			es.shutdownNow();
			PluginHandle.destroy();
		} catch (Exception e) {
			logger.error("An exception occur when the project distroy",e);
		}
	}

	// ==============================================================
	public void addIgnoreMapping(ServletContext context) {
		ServletRegistration defaultServlet = context.getServletRegistration("default");
		if (defaultServlet != null) {
			defaultServlet.addMapping("/favicon.ico");
			String IGNORE_PATH = FormatUtil.toStringTrim(AppConstant.CONFIG.AppIgnorePath.getValue());
			if (IGNORE_PATH.length() > 0) {
				defaultServlet.addMapping(IGNORE_PATH + "*");
			}
		}
	}
}
